//截流
export function throttle(
  fn,
  options = { wait: 1000, leading: true, trailing: false }
) {
  const { wait, leading, trailing } = options;
  let timer = null;
  let previous = 0;
  return function (...args) {
    let now = +new Date();
    if (!previous && !leading) previous = now;
    let remaining = wait - (now - previous);
    if (remaining <= 0 || remaining > wait) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      previous = now;
      fn.apply(this, args);
    } else if (!timer && trailing) {
      timer = setTimeout(() => {
        previous = leading ? 0 : +new Date();
        timer = null;
        fn.apply(this, args);
      }, remaining);
    }
  };
}

//防抖
export function debounce(fn, options = { wait: 1000, immediate: true }) {
  const { wait, immediate } = options;
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    if (immediate) {
      let callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      if (callNow) fn.apply(this, args);
    } else {
      timer = setTimeout(() => {
        fn.apply(this, args);
      }, wait);
    }
  };
}
